//
//  TGChooseFile.m
//  TongGuanLease
//
//  Created by Henghuitong on 2022/6/22.
//

#import "TGChooseFile.h"
//#import "GetMIMEType.h"
#import "MBProgressHUD+RY.h"

@implementation UploadFailedModel

@end


@interface TGChooseFile ()<UIDocumentPickerDelegate, UIDocumentInteractionControllerDelegate>

@property (nonatomic,copy)void (^chooseFileSuccess)(NSArray *array);

@property (nonatomic, copy) NSMutableArray *responseDataArray;
@property (nonatomic, copy) NSMutableArray *failureArray;

@property (nonatomic, strong) MBProgressHUD *hud;

@end



@implementation TGChooseFile


-(NSMutableArray *)failureArray
{
    if (!_failureArray)
    {
        _failureArray = [[NSMutableArray alloc]initWithCapacity:0];
    }
    
    return _failureArray;
    
}


-(NSMutableArray *)responseDataArray
{
    if (!_responseDataArray)
    {
        _responseDataArray = [[NSMutableArray alloc]initWithCapacity:0];
    }
    
    return _responseDataArray;
    
}

+ (instancetype)sharedInstance
{
    static TGChooseFile *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[TGChooseFile alloc] init];
    });
    return instance;
}

-(void)chooseFileWithSelectVC:(UIViewController *)presentVC success:(ChooseFileSuccess)success
{
    self.chooseFileSuccess = success;
    // 设置文件类型
    
//    NSArray *documentTypes = @[@"com.adobe.pdf"];
//    NSArray *documentTypes = @[@"public.content",
//                               @"public.text",
//                               @"public.source-code",
//                               @"public.image",
//                               @"public.audiovisual-content",
//                               @"com.adobe.pdf",
//                               @"com.apple.keynote.key",
//                               @"com.microsoft.word.doc",
//                               @"com.microsoft.excel.xls",
//                               @"com.microsoft.powerpoint.ppt",
//                               @"com.microsoft.powerpoint.pptx",@"com.microsoft.word.docx",@"com.microsoft.excel.xlsx",@"public.avi",@"public.3gpp",@"public.mpeg-4",@"com.compuserve.gif",@"public.jpeg",@"public.png",@"public.plain-text"];
    NSArray *documentTypes = @[@"public.audiovisual-content"];

    UIDocumentPickerViewController *documentPickerViewController = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:documentTypes inMode:UIDocumentPickerModeOpen];
    documentPickerViewController.delegate = self;
    documentPickerViewController.modalPresentationStyle = UIModalPresentationFullScreen;
    if (@available(iOS 11.0, *)) {
        documentPickerViewController.allowsMultipleSelection = YES;
    } else {
        // Fallback on earlier versions
    }
    dispatch_async(dispatch_get_main_queue(), ^(void){
        [presentVC presentViewController:documentPickerViewController animated:YES completion:nil];
    });

 
}



#pragma mark 点击取消文件选择

- (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller{
//    /// 设置回UIScrollViewContentInsetAdjustmentNever
//    if (@available(iOS 11, *)) {
//        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//    }
}

#pragma mark 点击选择文件结果

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls
{
    NSLog(@"多选urls-------- %@",urls);
    [self handleDocumentPicker:controller didPickDocumentsAtURLs:urls];
}

- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
{
    
    NSLog(@"单选选url-------- %@",url);
    [self handleDocumentPicker:controller didPickDocumentsAtURLs:@[url]];

}

- (void)handleDocumentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray <NSURL *>*)urls
{
    // 将文件复制到Cache文件夹下
    NSArray *newUrls = [self copyFilesToCacheWithOriginalUrls:urls];
    NSLog(@"newUrls===%@",newUrls);
    
    
    if(self.responseDataArray.count != 0)
    {
        [self.responseDataArray removeAllObjects];
    }
    
    if(self.failureArray.count != 0)
    {
        [self.failureArray removeAllObjects];
    }
    
//    [TGProgressHUD showHUD:nil];
    self.hud = [MBProgressHUD showMessage:@"上传中..." toView:self.getCurrentVC.view];
    
    // 创建一个队列
    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    // 设置最大线程数
    queue.maxConcurrentOperationCount = 1;
    
    //创建一个队列数组
    NSMutableArray *operaQueueArray = [NSMutableArray array];
    
     for (NSInteger i = 0; i < newUrls.count; i++) {

         NSURL *newURL = newUrls[i];


         NSBlockOperation *blockOpera = [NSBlockOperation blockOperationWithBlock:^{
            
             dispatch_semaphore_t semaphore = dispatch_semaphore_create(0); //默认创建的信号为0
             //网络请求
             
             [TGNetworkManager uploadFileWithFileUrl:newURL filePath:@"CONTRACT_SERVICE" success:^(TGResponseItem *responseItem) {
                
                 NSLog(@"返回数据=====%@",responseItem.data);
                 
                 dispatch_semaphore_signal(semaphore); //这里请求成功信号量 +1 为1

                 if (responseItem.success) {
                     TGUrlInfoModel *infoModel = [TGUrlInfoModel modelWithJSON:responseItem.data];
                     if (infoModel.size > 200*1024*1024) {
                         [TGGCD executeAfterTime:0.5 task:^{
                             [TGProgressHUD showHUDTip:@"该音频大于200M无法上传，请选择其他音频"];
                         }];
                         return;
                     }
                     infoModel.size = infoModel.size/1024/1024.0;
//                     infoModel.createTime = [NSDate date].getDateStringYMDHMS;
                     
                     [self.responseDataArray addObject:infoModel];
                     
                 }else
                 {
                     NSLog(@"message=====%@",responseItem.message);

                     //读取文件
                     NSString *fileName = [newURL lastPathComponent];
                     NSLog(@"文件名称=== %@",fileName);
        
                     UploadFailedModel *model = [[UploadFailedModel alloc] init];
                     model.fileName = fileName;
                     model.failureMessage = responseItem.message;
                     [self.failureArray addObject:model];
                 }
        
             } failure:^(NSError *error) {
                 dispatch_semaphore_signal(semaphore); //这里请求失败信号量 +1 为1
             }];
            
             dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER); //走到这里如果信号量为0 则不再执行下面的代码 一直等待 信号量不是0 出现 才会执行下面代码,然后信号量为 - 1
         }];

         //将创建的任务添加到数组中
         [operaQueueArray addObject:blockOpera];
     }
    
     //添加依赖关系
     for (int i = 0; i < operaQueueArray.count; i++) {
         if (i > 0) {
             [operaQueueArray[i] addDependency:operaQueueArray[i - 1]];
         }
     }
    
    [queue addOperations:operaQueueArray waitUntilFinished:NO];
    [queue addObserver:self forKeyPath:@"operationCount" options:0 context:nil];
    
}

//监听网络请求
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {

    if ([keyPath isEqualToString:@"operationCount"]) {
        NSOperationQueue *queue = (NSOperationQueue *)object;
        if (queue.operationCount == 0) {
        //主线程刷新界面
          dispatch_async(dispatch_get_main_queue(), ^{
            
//              [TGProgressHUD dismissMPHUD];
              [self.hud hideAnimated:YES];
              
              
              NSLog(@"主线程刷新界面");
              NSLog(@"responseDataArray====%@",self.responseDataArray);
              
              if(self.responseDataArray.count != 0)
              {
                  if(self.chooseFileSuccess)
                  {
                      self.chooseFileSuccess(self.responseDataArray);
                  }
              }
              
              if(self.failureArray.count == 0)
              {

//                  [TGProgressHUD showMBHUDErrorTip:@"上传成功"];
//                  [MBProgressHUD showText:@"上传成功"];
                  
              }else
              {
                
                
                      
                  NSMutableString *str  = [NSMutableString string];

                  for(UploadFailedModel *model in self.failureArray)
                  {
                      [str appendString:model.fileName];
                      [str appendString:model.failureMessage.length > 0 ? model.failureMessage : @"上传失败"];
                      [str appendString:@"\n"];
                  }
                  [TGLEEAlert alertTitle:@"上传失败的文件" message:str];
              }
              
              
          });
        }
    }
}



- (NSArray<NSURL *> *)copyFilesToCacheWithOriginalUrls:(NSArray <NSURL *>*)urls
{
    if (urls == nil || urls.count == 0) {
           return @[];
       }
    
    
    NSMutableArray<NSURL *> *arrFileUrls = [NSMutableArray new];
    long currMillisecond = [[NSDate date] timeIntervalSince1970] * 1000;
    NSFileManager *fileManager = [NSFileManager defaultManager];
      
    
//    for(int i = 0; i < array.count; i++)
       
    for (NSURL *url in urls)
    {
        //获取授权
        BOOL fileUrlAuthozied = [url startAccessingSecurityScopedResource];
        if(fileUrlAuthozied){
            //通过文件协调工具来得到新的文件地址，以此得到文件保护功能
            NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
            NSError *error;
            [fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
                
                //读取文件
                NSString *fileName = [newURL lastPathComponent];
                NSLog(@"文件名称=== %@",fileName);
   
                
                
                NSString *cachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory
                                                                          , NSUserDomainMask
                                                                          , YES).lastObject;

                NSString *finderPath = [NSString stringWithFormat:@"%@/%ld/", cachePath, currMillisecond];
                if ([fileManager fileExistsAtPath:finderPath] == NO) {
                    [fileManager createDirectoryAtPath:finderPath withIntermediateDirectories:YES attributes:nil error:nil];
                }

                NSString *filePath = [finderPath stringByAppendingPathComponent:fileName];
                if ([fileManager fileExistsAtPath:filePath]) {
                    NSError *error = nil;
                    [fileManager removeItemAtPath:filePath error:&error];
                    if (error) NSLog(@"error : %@", error);
                }

                NSData *fileData = [NSData dataWithContentsOfURL:newURL];


                BOOL success =  [fileData writeToFile:filePath atomically:YES];

                if (success) {
                    NSLog(@"file copy success");
                    NSLog(@"filePath==%@",filePath);
//                    NSString *fileMIMETypeWithCAPI = [GetMIMEType getMIMETypeWithCAPIAtFilePath:filePath];
//                    NSLog(@"fileMIMETypeWithCAPI===%@",fileMIMETypeWithCAPI);

                    [arrFileUrls addObject:[NSURL fileURLWithPath:filePath]];
                }else{
                    NSLog(@"file copy fail");
                }
                
                
            }];
            
        }else{
            
        }

    }
    
    return arrFileUrls;
    
}

/*
 NSURL *newURL =  [newUrls firstObject];
  NSLog(@"选择的文件地址=== %@",newURL.absoluteString);
  NSString  *string = [newURL.absoluteString stringByReplacingOccurrencesOfString:@"file://" withString:@""];
  NSLog(@"string=== %@",string);
  NSString *fileMIMETypeWithCAPI = [GetMIMEType getMIMETypeWithCAPIAtFilePath:string];
  NSLog(@"fileMIMETypeWithCAPI===%@",fileMIMETypeWithCAPI);
  NSLog(@"newURL-------- %@",newURL);
  //读取文件
  NSString *fileName = [newURL lastPathComponent];
  NSLog(@"文件名称=== %@",fileName);
  NSError *error = nil;
  NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
  [TGNetworkManager uploadFileWithFileData:fileData fileName:fileName filePath:@"CRM_SERVICE" mimeType:fileMIMETypeWithCAPI success:^(TGResponseItem *responseItem) {


      if (responseItem.success) {
          NSLog(@"上传文件成功返回数据=====%@",responseItem.data);
      
      }else
      {
          
      }

  } failure:^(NSError *error) {
      [TGProgressHUD showHUDTipNetError];
  }];
  
 */

/*
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url {
    /// 设置回UIScrollViewContentInsetAdjustmentNever
//    if (@available(iOS 11, *)) {
//        UIScrollView.appearance.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
//    }

    //获取授权
    BOOL fileUrlAuthozied = [url startAccessingSecurityScopedResource];
    if(fileUrlAuthozied){
        //通过文件协调工具来得到新的文件地址，以此得到文件保护功能
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        [fileCoordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
          
            NSLog(@"选择的文件地址=== %@",newURL.absoluteString);
            NSLog(@"newURL-------- %@",newURL);
            
            //读取文件
            NSString *fileName = [newURL lastPathComponent];
            NSLog(@"文件名称=== %@",fileName);

            NSError *error = nil;
            NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
   
        
            NSString *newNameStr = [fileName stringByRemovingPercentEncoding];
            NSArray *fileArray = [newNameStr componentsSeparatedByString:@"."];
//            NSString *mimeType = [NSString stringWithFormat:@"application/%@",fileArray.lastObject];
            NSString *mimeType = [NSString stringWithFormat:@"file/%@",fileArray.lastObject];


            [TGProgressHUD showHUD:nil];
            [TGNetworkManager uploadFileWithFileData:fileData fileUrl:newURL.absoluteString fileName:fileName filePath:@"CRM_SERVICE" mimeType:mimeType success:^(TGResponseItem *responseItem) {

                [TGProgressHUD dismissMPHUD];

                if (responseItem.success) {
                    NSLog(@"上传文件成功返回数据=====%@",responseItem.data);
                    if(self.chooseFileSuccess)
                    {
                        self.chooseFileSuccess(responseItem.data);
                    }
//                    [TGProgressHUD showMBHUDErrorTip:@"上传成功"];

                }else
                {
                    [TGProgressHUD showMBHUDErrorTip:responseItem.message];
                }

            } failure:^(NSError *error) {
                [TGProgressHUD showHUDTipNetError];
            }];
            
        }];
        
        [url stopAccessingSecurityScopedResource];
        
    }else{
        [TGProgressHUD showMBHUDErrorTip:@"授权失败"];
    }
    
}

*/

@end
